package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    // 菜品分页
    @GetMapping("/page")
    public R<Page<Category>> pageCategory(Integer page,Integer pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        // 加一个排序的条件
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,lqw);
        return  R.success(pageInfo);
    }

    // 删除
    // 判断
    // 判断要删除的这个类是否又菜品
    // sql: select count(*) from dish where categoty_id=?
    // if(count>0 ){
    // 已经有菜品了
    // }
    // sql: select count(*) from set_meal where categoty_id=?

    @DeleteMapping
    public R<String> deleteCategory(Long id){
        // categoryService.removeById(id);
        // 还要继续把菜品删除
        categoryService.removeCategoryById(id);
         return  R.success("删除成功");
    }
    @PutMapping
    public R<String> updateCategory(@RequestBody  Category category){
        category.setUpdateTime(null);
        category.setUpdateUser(null);
        categoryService.updateById(category);
        return  R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> getCatrgoryList(Integer type){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type!=null ,Category::getType,type);
        lqw.orderByAsc(Category::getSort);
        return  R.success(categoryService.list(lqw));

    }
}